﻿using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Core;
using AJWPFAdmin.Core.Validation;
using AJWPFAdmin.Services.EF;
using MaterialDesignExtensions.Controls;
using Newtonsoft.Json.Linq;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using Microsoft.EntityFrameworkCore;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Core.Enums;
using DocumentFormat.OpenXml.Office2010.Drawing.Charts;
using DocumentFormat.OpenXml.Spreadsheet;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Services.AppointAPI;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using Masuit.Tools;
using AJWPFAdmin.Core.Components.ViewModels;
using AJWPFAdmin.Core.Components.Views;
using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.HardwareSDKS.EQLED;
using AngleSharp.Css;
using EntranceGuardManager.Modules.Main.Views;
using Prism.Services.Dialogs;
using Masuit.Tools.Hardware;
using System.Windows;
using Org.BouncyCastle.Asn1.X509;
using DocumentFormat.OpenXml.CustomXmlSchemaReferences;
using System.Reflection;
using Prism.Ioc;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using MaterialDesignThemes.Wpf;
using DocumentFormat.OpenXml.Office2010.Excel;
using AJWPFAdmin.Core.Crypto.SMCrypto;
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using AJWPFAdmin.Services.Migrations;
using AJWPFAdmin.Services.AppointAPI.ChengDu;
using AJWPFAdmin.Services;

namespace EntranceGuardManager.Modules.Main.ViewModels
{
    public class OtherConfigViewModel : AnnotationValidationViewModel, INavigationAware
    {

        private bool _loading;
        public bool Loading
        {
            get { return _loading; }
            set
            {
                SetProperty(ref _loading, value);
                SaveCmd.RaiseCanExecuteChanged();
            }
        }

        private Dictionary<string, FreightUnit> _freightUnitOptions;
        public Dictionary<string, FreightUnit> FreightUnitOptions
        {
            get => _freightUnitOptions;
            set
            {
                SetProperty(ref _freightUnitOptions, value);
            }
        }

        #region PopUp

        public class PopupContainer : BindableBase
        {
            private bool _ledFieldPopupOpen;
            public bool LedFieldPopupOpen
            {
                get { return _ledFieldPopupOpen; }
                set { SetProperty(ref _ledFieldPopupOpen, value); }
            }

            private bool _pushUrlPopupOpen;
            public bool PushUrlPopupOpen
            {
                get { return _pushUrlPopupOpen; }
                set { SetProperty(ref _pushUrlPopupOpen, value); }
            }
        }

        private PopupContainer _popupContainerBind;
        public PopupContainer PopupContainerBind
        {
            get { return _popupContainerBind; }
            set { SetProperty(ref _popupContainerBind, value); }
        }

        private DelegateCommand<string> _togglePopupCmd;
        public DelegateCommand<string> TogglePopupCmd =>
            _togglePopupCmd ?? (_togglePopupCmd = new DelegateCommand<string>(ExecuteTogglePopupCmd));

        void ExecuteTogglePopupCmd(string param)
        {
            var prop = PopupContainerBind.GetType().GetProperty(param);
            if (prop == null)
            {
                return;
            }

            prop.SetValue(PopupContainerBind, !(bool)prop.GetValue(PopupContainerBind));
        }

        #endregion

        #region 统计配置表单

        private PassagewayStatisticType _passagewayStatistic_Type;
        [Display(Name = "统计方式")]
        [Required(ErrorMessage = "{0}必填")]
        public PassagewayStatisticType PassagewayStatistic_Type
        {
            get { return _passagewayStatistic_Type; }
            set { SetProperty(ref _passagewayStatistic_Type, value); }
        }

        private Dictionary<string, PassagewayStatisticType> _passagewayStatisticOptions;
        public Dictionary<string, PassagewayStatisticType> PassagewayStatisticOptions
        {
            get { return _passagewayStatisticOptions; }
            set { SetProperty(ref _passagewayStatisticOptions, value); }
        }

        #endregion

        #region 接口配置表单

        private DefaultAppointAPI.APIConfig _globalAPIConfig;
        public DefaultAppointAPI.APIConfig GlobalAPIConfig
        {
            get => _globalAPIConfig;
            set => SetProperty(ref _globalAPIConfig, value);
        }

        private ObservableCollection<AppointAPIBase> _apiOptions;
        public ObservableCollection<AppointAPIBase> APIOptions
        {
            get { return _apiOptions; }
            set { SetProperty(ref _apiOptions, value); }
        }

        private ObservableCollection<DynamicFormItemSchema> _dynamicFormItemSchemas;
        public ObservableCollection<DynamicFormItemSchema> DynamicFormItemSchemas
        {
            get { return _dynamicFormItemSchemas; }
            set { SetProperty(ref _dynamicFormItemSchemas, value); }
        }

        #endregion

        #region 识别配置表单

        private string _carIdentificationConfig_PushUrl;
        [Display(Name = "推送地址")]
        [AJFormUrlField(ErrorMessage = "推送地址有误")]
        public string CarIdentificationConfig_PushUrl
        {
            get { return _carIdentificationConfig_PushUrl; }
            set { SetProperty(ref _carIdentificationConfig_PushUrl, value); }
        }

        private string _carIdentificationConfig_ImageSavePath;
        [Display(Name = "图片存放路径")]
        [Required(ErrorMessage = "{0}必填")]
        public string CarIdentificationConfig_ImageSavePath
        {
            get { return _carIdentificationConfig_ImageSavePath; }
            set { SetProperty(ref _carIdentificationConfig_ImageSavePath, value); }
        }

        private CarIdentificationConfig.StoreType _carIdentificationConfig_StoreType;
        [Display(Name = "图片存放类型")]
        public CarIdentificationConfig.StoreType CarIdentificationConfig_StoreType
        {
            get { return _carIdentificationConfig_StoreType; }
            set
            {
                if (SetProperty(ref _carIdentificationConfig_StoreType, value))
                {
                    CarIdentificationConfig_ImageSavePath = string.Empty;
                }
            }
        }

        #endregion

        #region LED配置表单

        private DelegateCommand<EQLEDControlConfigModel> _ledCfg_EQLED_EditCmd;
        public DelegateCommand<EQLEDControlConfigModel> LEDCfg_EQLED_EditCmd =>
            _ledCfg_EQLED_EditCmd ?? (_ledCfg_EQLED_EditCmd = new DelegateCommand<EQLEDControlConfigModel>(ExecuteLEDCfg_EQLED_EditCmd));

        void ExecuteLEDCfg_EQLED_EditCmd(EQLEDControlConfigModel parameter)
        {
            var @params = new DialogParameters
            {
                { "data", parameter },
                { "source", _ledConfig.EQLEDs },
            };
            _dialogSvc.ShowDialog(nameof(EQLEDForm), @params, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    var newList = new List<EQLEDControlConfigModel>();
                    var newData = r.Parameters.GetValue<EQLEDControlConfigModel>("data");

                    if (parameter == null)
                    {
                        newList.AddRange(_ledConfig.EQLEDs);
                    }
                    else
                    {
                        newList.AddRange(_ledConfig.EQLEDs.Where(p => p.Id != newData.Id).ToList());
                    }
                    newList.Add(newData);
                    _ledConfig.EQLEDs = newList;
                    LEDCfg_EQLED_FetchOptions.RequestRefresh();
                }
            });
        }

        private DelegateCommand<EQLEDControlConfigModel> _ledCfg_EQLED_DeleteCmd;
        public DelegateCommand<EQLEDControlConfigModel> LEDCfg_EQLED_DeleteCmd =>
            _ledCfg_EQLED_DeleteCmd ?? (_ledCfg_EQLED_DeleteCmd = new DelegateCommand<EQLEDControlConfigModel>(ExecuteLEDCfg_EQLED_DeleteCmd));

        async void ExecuteLEDCfg_EQLED_DeleteCmd(EQLEDControlConfigModel parameter)
        {
            var confirm = await CommonUtil.ShowConfirmDialogAsync(new ConfirmationDialogArguments
            {
                Title = "删除确认",
                Message = $"即将删除 {parameter.CardType} ?"
            });

            if (confirm)
            {
                var newList = new List<EQLEDControlConfigModel>();
                newList.AddRange(_ledConfig.EQLEDs.Where(p => p.Id != parameter.Id).ToList());
                _ledConfig.EQLEDs = newList;
                LEDCfg_EQLED_FetchOptions.RequestRefresh();
            }
        }

        private List<AJTableColumnItem> _ledCfg_QELED_Columns;
        public List<AJTableColumnItem> LEDCfg_EQLED_Columns
        {
            get { return _ledCfg_QELED_Columns; }
            set { SetProperty(ref _ledCfg_QELED_Columns, value); }
        }

        private AJTableSearchFormConfig _ledCfg_QELED_FormConfig;
        public AJTableSearchFormConfig LEDCfg_EQLED_FormConfig
        {
            get { return _ledCfg_QELED_FormConfig; }
            set { SetProperty(ref _ledCfg_QELED_FormConfig, value); }
        }

        private AJTableFetchOptions _ledCfg_QELED_FetchOptions;
        public AJTableFetchOptions LEDCfg_EQLED_FetchOptions
        {
            get
            {
                return _ledCfg_QELED_FetchOptions;
            }
            set
            {
                SetProperty(ref _ledCfg_QELED_FetchOptions, value);
            }
        }

        private string _camera_ledCfg_Entrance_Idle;
        [Display(Name = "相机LED入口空闲文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string CameraLEDCfg_Entrance_Idle
        {
            get { return _camera_ledCfg_Entrance_Idle; }
            set { SetProperty(ref _camera_ledCfg_Entrance_Idle, value); }
        }

        private string _ledCfg_Entrance_Idle;
        [Display(Name = "LED入口空闲文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string LEDCfg_Entrance_Idle
        {
            get { return _ledCfg_Entrance_Idle; }
            set { SetProperty(ref _ledCfg_Entrance_Idle, value); }
        }

        private string _ledCfg_Entrance_Passing;
        [Display(Name = "LED入口正在通行文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string LEDCfg_Entrance_Passing
        {
            get { return _ledCfg_Entrance_Passing; }
            set { SetProperty(ref _ledCfg_Entrance_Passing, value); }
        }

        private string _camera_ledCfg_Entrance_Passing;
        [Display(Name = "相机LED入口正在通行文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string CameraLEDCfg_Entrance_Passing
        {
            get { return _camera_ledCfg_Entrance_Passing; }
            set { SetProperty(ref _camera_ledCfg_Entrance_Passing, value); }
        }

        private string _ledCfg_Entrance_Passed;
        [Display(Name = "LED入口通行完成文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string LEDCfg_Entrance_Passed
        {
            get { return _ledCfg_Entrance_Passed; }
            set { SetProperty(ref _ledCfg_Entrance_Passed, value); }
        }

        private string _ledCfg_Entrance_Alarm;
        [Display(Name = "LED入口告警文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string LEDCfg_Entrance_Alarm
        {
            get { return _ledCfg_Entrance_Alarm; }
            set { SetProperty(ref _ledCfg_Entrance_Alarm, value); }
        }

        private string _camera_ledCfg_Entrance_Passed;
        [Display(Name = "相机LED入口通行完成文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string CameraLEDCfg_Entrance_Passed
        {
            get { return _camera_ledCfg_Entrance_Passed; }
            set { SetProperty(ref _camera_ledCfg_Entrance_Passed, value); }
        }

        private string _camera_ledCfg_Entrance_Alarm;
        [Display(Name = "相机LED入口通行告警文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string CameraLEDCfg_Entrance_Alarm
        {
            get { return _camera_ledCfg_Entrance_Alarm; }
            set { SetProperty(ref _camera_ledCfg_Entrance_Alarm, value); }
        }

        private string _ledCfg_Exit_Idle;
        [Display(Name = "LED出口空闲文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string LEDCfg_Exit_Idle
        {
            get { return _ledCfg_Exit_Idle; }
            set { SetProperty(ref _ledCfg_Exit_Idle, value); }
        }

        private string _camera_ledCfg_Exit_Idle;
        [Display(Name = "相机LED出口空闲文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string CameraLEDCfg_Exit_Idle
        {
            get { return _camera_ledCfg_Exit_Idle; }
            set { SetProperty(ref _camera_ledCfg_Exit_Idle, value); }
        }

        private string _ledCfg_Exit_Passing;
        [Display(Name = "LED出口正在通行文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string LEDCfg_Exit_Passing
        {
            get { return _ledCfg_Exit_Passing; }
            set { SetProperty(ref _ledCfg_Exit_Passing, value); }
        }

        private string _camera_ledCfg_Exit_Passing;
        [Display(Name = "相机LED出口正在通行文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string CameraLEDCfg_Exit_Passing
        {
            get { return _camera_ledCfg_Exit_Passing; }
            set { SetProperty(ref _camera_ledCfg_Exit_Passing, value); }
        }

        private string _ledCfg_Exit_Passed;
        [Display(Name = "LED出口通行完成文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string LEDCfg_Exit_Passed
        {
            get { return _ledCfg_Exit_Passed; }
            set { SetProperty(ref _ledCfg_Exit_Passed, value); }
        }

        private string _ledCfg_Exit_Alarm;
        [Display(Name = "LED出口告警文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string LEDCfg_Exit_Alarm
        {
            get { return _ledCfg_Exit_Alarm; }
            set { SetProperty(ref _ledCfg_Exit_Alarm, value); }
        }

        private string _camera_ledCfg_Exit_Passed;
        [Display(Name = "相机LED出口通行完成文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string CameraLEDCfg_Exit_Passed
        {
            get { return _camera_ledCfg_Exit_Passed; }
            set { SetProperty(ref _camera_ledCfg_Exit_Passed, value); }
        }

        private string _camera_ledCfg_Exit_Alarm;
        [Display(Name = "相机LED出口告警文案")]
        [Required(ErrorMessage = "{0}必填")]
        public string CameraLEDCfg_Exit_Alarm
        {
            get { return _camera_ledCfg_Exit_Alarm; }
            set { SetProperty(ref _camera_ledCfg_Exit_Alarm, value); }
        }

        #endregion

        #region 出入控制配置表单

        private EntryConfig _entryConfig;
        public EntryConfig EntryConfig
        {
            get => _entryConfig;
            set
            {
                SetProperty(ref _entryConfig, value);
            }
        }

        #endregion

        private DelegateCommand<SelectionChangedEventArgs> _apiOptionSelectionChangedCmd;
        public DelegateCommand<SelectionChangedEventArgs> APIOptionSelectionChangedCmd =>
            _apiOptionSelectionChangedCmd ?? (_apiOptionSelectionChangedCmd = new DelegateCommand<SelectionChangedEventArgs>(ExecuteAPIOptionSelectionChangedCmd));

        void ExecuteAPIOptionSelectionChangedCmd(SelectionChangedEventArgs parameter)
        {
            parameter.Handled = true;
            if (parameter.AddedItems?.Count > 0)
            {
                if (parameter.AddedItems[0] is AppointAPIBase api)
                {
                    foreach (var item in APIOptions)
                    {
                        item.Checked = item.Config.Key == api.Config.Key;
                    }
                    DynamicFormItemSchemas = api.GetSchemas();
                }
            }
        }

        private CarIdentificationConfig _carIdentificationConfig;
        private LEDConfig _ledConfig;
        private PassagewayStatisticConfig _passagewayStatisticConfig;


        private DbService db;
        private IDialogService _dialogSvc;
        private AppointAPISvc _appointSvc;
        private IContainerProvider _svcProvider;
        private MainApplicationBridgeService _mainApplicationBridgeSvc;

        public OtherConfigViewModel(DbService dbIns,
            IEventAggregator eventAggregator,
            IDialogService dialogSvc,
            AppointAPISvc appointSvc,
            IContainerProvider svcProvider,
            MainApplicationBridgeService mainApplicationBridgeSvc)
        {
            db = dbIns;
            _dialogSvc = dialogSvc;
            _svcProvider = svcProvider;
            _mainApplicationBridgeSvc = mainApplicationBridgeSvc;
            eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>().Subscribe(() =>
            {
                Loading = false;
            });
            _appointSvc = appointSvc;
            PopupContainerBind = new PopupContainer();
            FreightUnitOptions = CommonUtil.EnumToDictionary<FreightUnit>(null);
        }

        private DelegateCommand _openFileDialogCmd;
        public DelegateCommand OpenFileDialogCmd =>
            _openFileDialogCmd ?? (_openFileDialogCmd = new DelegateCommand(ExecuteOpenFileDialogCmd));

        void ExecuteOpenFileDialogCmd()
        {
            var folder = _mainApplicationBridgeSvc
                .GetFolderFromDialog(CarIdentificationConfig_ImageSavePath);

            if (string.IsNullOrWhiteSpace(folder))
            {
                return;
            }

            CarIdentificationConfig_ImageSavePath = folder;
        }

        private DelegateCommand _saveCmd;
        public DelegateCommand SaveCmd =>
            _saveCmd ?? (_saveCmd = new DelegateCommand(ExecuteSaveCmdAsync, CanExecuteSaveCmd));
        async void ExecuteSaveCmdAsync()
        {
            if (!ValidateModel())
            {
                AJCommonDialog.ShowDialog(new AJCommonDialogViewModel.AJCommonDialogParams
                {
                    Title = "提示",
                    Message = "表单校验失败,请检查所填数据",
                    Detail = string.Join(";", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString()))
                });
                SaveCmd.RaiseCanExecuteChanged();
                return;
            }

            Loading = true;
            string newConfigJson = string.Empty;
            string oldConfigJson = string.Empty;
            var modifyOptions = this.APIOptions.Where(x => x.Checked).FirstOrDefault();
            if (modifyOptions != null)
            {
                oldConfigJson = db.SystemConfigDictionaries.FirstOrDefault(p => p.Key == modifyOptions.Config.Key).StringValue;
            }
            FillPassagewayStatisticConfigForm();
            FillThirdPartyCarInfoAPIConfigForm();
            FillCarIdentificationConfigForm();
            FillLEDConfigForm();
            FillEntryConfigForm();


            await db.SaveChangesAsync();
            AJCommonDialog.ShowDialog(new AJCommonDialogViewModel.AJCommonDialogParams
            {
                Title = "提示",
                Message = "保存成功!"
            });
            //var wq = "BCW0dM/Z5i+Sx7IuSOVKoN0pfWR3pEHKYYWkItlNlIMN8LBY6ZON3DOpJUBxebBo65pFafe+EQQXhLq21kdG7UZ9MwE3ts6EL4SN3IXrJa4XhMK60IcLzEkONndqtH2Y01gGaycz/Aa4PNt54ErhqzcK/h8RzC2Dzv5HLmoRwyyOYk4TdSIQ+uPkpe3aoplMojxRjsxwOPmJAEqexmkc3c8Kx2GDDFj3KeP9XWBothR77VLZRVhbXQC7JN8sU/W+PijZf/KNbGri6ovjjt+qurIHyRM=";
            //var base64PrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgL9ZRFluKZ1LpI/pm6yendLB0czgnGDYtvjunlWMuukOgCgYIKoEcz1UBgi2hRANCAARctl9vIGbAP6qxvQbqqvRKs0pJhRSKRQEDVvCP7FRaSKAwQDTT8s8zuK4r62FWeP2RHSJaufcFnkh9cYHa6kVX";


            //var input = Convert.FromBase64String(wq);
            //var qewe = SM2.Decrypt(input, base64PrivateKey);
            //var encryptedBodyBytes = SM2.EncryptToBase64("{\"clientId\":\"QDMJ_021_QDBD\",\"clientSecret\":\"6dfc849b70aa8aafcfa8ee0669ebff62\"}", "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEXLZfbyBmwD+qsb0G6qr0SrNKSYUUikUBA1bwj+xUWkigMEA00/LPM7iuK+thVnj9kR0iWrn3BZ5IfXGB2upFVw==");
            //var ship = new ShippingRecordParams ();
            //ship.Record = new ShippingRecord
            //{
            //    Direction = PassagewayDirection.进,
            //    DeviceCode = "test",
            //    ShipStartDate = DateTime.Now,
            //    ShipEndDate = DateTime.Now,
            //    CarNo = "CarNo",
            //    PlateColor = CarPlateColor.黄牌,
            //    TypeName = "2",
            //    EmissionStandard = EmissionStandard.国五,
            //    FuelTypeName = "1",
            //    Id = 32132133,
            //    InCaptureFile = ""
            //};
            //var ret1 = await _appointSvc.API.UploadShippingRecordAsync(ship );

            //根据需要调用企业信息同步数据(目前只有赣州的需要)
            if (modifyOptions != null)
            {
                newConfigJson = db.SystemConfigDictionaries.FirstOrDefault(p => p.Key == modifyOptions.Config.Key).StringValue;
                if (oldConfigJson != newConfigJson)
                {
                    var ret = await _appointSvc.API.UploadComanyInfoAsync(newConfigJson);
                }
            }
            Loading = false;
        }

        bool CanExecuteSaveCmd()
        {
            return !HasErrors;
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            Loading = true;

            InitPassagewayStatisticConfigForm();
            InitThirdpartyCarInfoAPIConfigForm();
            InitCarIdentificationConfigForm();
            InitLEDConfigForm();
            InitEntryConfigForm();

            Loading = false;
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        /// <summary>
        /// 统计配置表单初始化
        /// </summary>
        private void InitPassagewayStatisticConfigForm()
        {
            _passagewayStatisticConfig = CommonUtil
                .TryGetJSONObject<PassagewayStatisticConfig>(db.SystemConfigDictionaries
                .FirstOrDefault(p => p.Key == SystemConfigKey.PassagewayStatisticConfig)
                ?.StringValue) ?? new PassagewayStatisticConfig();

            _passagewayStatistic_Type = _passagewayStatisticConfig.Type;

            PassagewayStatisticOptions = CommonUtil.EnumToDictionary<PassagewayStatisticType>((key) =>
            {
                switch (key)
                {
                    case PassagewayStatisticType.Once:
                        return "经过一次";
                    case PassagewayStatisticType.Twice:
                        return "一进一出";
                    default:
                        return "--";
                }
            });


        }

        /// <summary>
        /// 填充更改统计配置表单
        /// </summary>
        private void FillPassagewayStatisticConfigForm()
        {
            var cfg = db.SystemConfigDictionaries
                .FirstOrDefault(p => p.Key == SystemConfigKey.PassagewayStatisticConfig);

            _passagewayStatisticConfig.Type = PassagewayStatistic_Type;

            if (cfg == null)
            {
                db.SystemConfigDictionaries.Add(new SystemConfigDictionary
                {
                    Key = SystemConfigKey.PassagewayStatisticConfig,
                    StringValue = CommonUtil.AJSerializeObject(_passagewayStatisticConfig),
                    CreateDate = DateTime.Now
                });
            }
            else
            {
                cfg.StringValue
                    = CommonUtil.AJSerializeObject(_passagewayStatisticConfig);
                db.Entry(cfg).State = EntityState.Modified;
            }
        }

        /// <summary>
        /// LED配置表单初始化
        /// </summary>
        private void InitLEDConfigForm()
        {
            _ledConfig = CommonUtil
                .TryGetJSONObject<LEDConfig>(db.SystemConfigDictionaries
                .FirstOrDefault(p => p.Key == SystemConfigKey.LEDConfig)
                ?.StringValue) ?? new LEDConfig();

            _ledConfig.Init();

            CameraLEDCfg_Entrance_Idle = _ledConfig.EntranceTextArray.ElementAtOrDefault(0);
            CameraLEDCfg_Entrance_Passing = _ledConfig.EntranceTextArray.ElementAtOrDefault(1);
            CameraLEDCfg_Entrance_Passed = _ledConfig.EntranceTextArray.ElementAtOrDefault(2);
            CameraLEDCfg_Entrance_Alarm = _ledConfig.EntranceTextArray.ElementAtOrDefault(3);

            CameraLEDCfg_Exit_Idle = _ledConfig.ExitTextArray.ElementAtOrDefault(0);
            CameraLEDCfg_Exit_Passing = _ledConfig.ExitTextArray.ElementAtOrDefault(1);
            CameraLEDCfg_Exit_Passed = _ledConfig.ExitTextArray.ElementAtOrDefault(2);
            CameraLEDCfg_Exit_Alarm = _ledConfig.ExitTextArray.ElementAtOrDefault(3);


            LEDCfg_Entrance_Idle = _ledConfig.LEDEntranceTextArray.ElementAtOrDefault(0);
            LEDCfg_Entrance_Passing = _ledConfig.LEDEntranceTextArray.ElementAtOrDefault(1);
            LEDCfg_Entrance_Passed = _ledConfig.LEDEntranceTextArray.ElementAtOrDefault(2);
            LEDCfg_Entrance_Alarm = _ledConfig.LEDEntranceTextArray.ElementAtOrDefault(3);

            LEDCfg_Exit_Idle = _ledConfig.LEDExitTextArray.ElementAtOrDefault(0);
            LEDCfg_Exit_Passing = _ledConfig.LEDExitTextArray.ElementAtOrDefault(1);
            LEDCfg_Exit_Passed = _ledConfig.LEDExitTextArray.ElementAtOrDefault(2);
            LEDCfg_Exit_Alarm = _ledConfig.LEDExitTextArray.ElementAtOrDefault(3);

            LEDCfg_EQLED_FetchOptions = new AJTableFetchOptions
            {
                Handle = (formCfg, pageCfg) =>
                {
                    _ledConfig.EQLEDs ??= new List<EQLEDControlConfigModel>();

                    return Task.FromResult(new AJTableFetchResult
                    {
                        Total = _ledConfig.EQLEDs.Count,
                        HasNext = false,
                        Rows = _ledConfig.EQLEDs
                    });
                }
            };

            LEDCfg_EQLED_FormConfig = new AJTableSearchFormConfig
            {
                Schemas = new ObservableCollection<AJTableSearchFormSchema>
                {

                },
                AdvFilterVisibility = System.Windows.Visibility.Collapsed,
                ExportVisibility = System.Windows.Visibility.Collapsed,
            };

            LEDCfg_EQLED_Columns = new List<AJTableColumnItem>
            {
                new AJTableColumnItem
                {
                    Title = "操作",
                    CustomTemplate = new AJTableCustomTemplate
                    {
                        Key = "LEDCfgEQLEDTableOperatioin"
                    },
                    Fixed = AJTableColumnFixedType.Right,
                    Width = new DataGridLength(160),
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.PassagewayNames),
                    Title = "关联道闸",
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.LineHeight),
                    Title = "每行高度",
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.CardType),
                    Title = "控制卡型号",
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.CardAddress),
                    Title = "控制卡地址"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.CommunicationMode),
                    Title = "通讯方式",
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.SerialNum),
                    Title = "串口号",
                    Formatter = new AJTableColumnFormatter
                    {
                        Handler = (val) =>
                        {
                            return $"COM{val}";
                        }
                    }
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.SerialBaud),
                    Title = "波特率",
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.NetPort),
                    Title = "网络端口",
                },
                 new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.IpAddress),
                    Title = "IP地址",
                },
                  new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.ScreenWidth),
                    Title = "屏幕宽度",
                },
                   new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.ScreenHeight),
                    Title = "屏幕高度",
                },
                    new AJTableColumnItem
                {
                    DataIndex = nameof(EQLEDControlConfigModel.ColorStyle),
                    Title = "屏幕颜色",
                },
            };
        }

        private void InitEntryConfigForm()
        {
            var cfg = CommonUtil
                .TryGetJSONObject<EntryConfig>(db.SystemConfigDictionaries
                .FirstOrDefault(p => p.Key == SystemConfigKey.EntryConfig)
                ?.StringValue) ?? new EntryConfig();

            if (cfg.EmissionStandardCfgItems.Count == 0)
            {
                cfg.InitDefault();
            }
            else
            {
                cfg.Prepare();
            }

            EntryConfig = cfg;
        }

        /// <summary>
        /// 填充更改LED配置表单
        /// </summary>
        private void FillLEDConfigForm()
        {
            var ledConfig = db.SystemConfigDictionaries
                .FirstOrDefault(p => p.Key == SystemConfigKey.LEDConfig);

            _ledConfig.EntranceTextArray[0] = CameraLEDCfg_Entrance_Idle;
            _ledConfig.EntranceTextArray[1] = CameraLEDCfg_Entrance_Passing;
            _ledConfig.EntranceTextArray[2] = CameraLEDCfg_Entrance_Passed;
            _ledConfig.EntranceTextArray[3] = CameraLEDCfg_Entrance_Alarm;

            _ledConfig.ExitTextArray[0] = CameraLEDCfg_Exit_Idle;
            _ledConfig.ExitTextArray[1] = CameraLEDCfg_Exit_Passing;
            _ledConfig.ExitTextArray[2] = CameraLEDCfg_Exit_Passed;
            _ledConfig.ExitTextArray[3] = CameraLEDCfg_Exit_Alarm;

            _ledConfig.LEDEntranceTextArray[0] = LEDCfg_Entrance_Idle;
            _ledConfig.LEDEntranceTextArray[1] = LEDCfg_Entrance_Passing;
            _ledConfig.LEDEntranceTextArray[2] = LEDCfg_Entrance_Passed;
            _ledConfig.LEDEntranceTextArray[3] = LEDCfg_Entrance_Alarm;

            _ledConfig.LEDExitTextArray[0] = LEDCfg_Exit_Idle;
            _ledConfig.LEDExitTextArray[1] = LEDCfg_Exit_Passing;
            _ledConfig.LEDExitTextArray[2] = LEDCfg_Exit_Passed;
            _ledConfig.LEDExitTextArray[3] = LEDCfg_Exit_Alarm;

            if (ledConfig == null)
            {
                db.SystemConfigDictionaries.Add(new SystemConfigDictionary
                {
                    Key = SystemConfigKey.LEDConfig,
                    StringValue = CommonUtil.AJSerializeObject(_ledConfig),
                    CreateDate = DateTime.Now
                });
            }
            else
            {
                ledConfig.StringValue
                    = CommonUtil.AJSerializeObject(_ledConfig);
                db.Entry(ledConfig).State = EntityState.Modified;
            }
        }

        /// <summary>
        /// 保存出入控制配置表单
        /// </summary>
        private void FillEntryConfigForm()
        {
            var cfg = db.SystemConfigDictionaries
                .FirstOrDefault(p => p.Key == SystemConfigKey.EntryConfig);

            if (EntryConfig.BelowOrEqualStandard5PassEndTimeInNextDay)
            {
                EntryConfig.BelowOrEqualStandard5PassEndTime = EntryConfig.BelowOrEqualStandard5PassEndTime.GetValueOrDefault().AddDays(1);
            }

            if (EntryConfig.BelowOrEqualStandard5PassStartTime > EntryConfig.BelowOrEqualStandard5PassEndTime)
            {
                ExceptionTool.FriendlyError($"开始时间不能大于结束时间", "国五及以下车辆进厂时间配置有误");
            }

            if (cfg == null)
            {
                db.SystemConfigDictionaries.Add(new SystemConfigDictionary
                {
                    Key = SystemConfigKey.EntryConfig,
                    StringValue = CommonUtil.AJSerializeObject(new
                    {
                        EntryConfig.EmissionStandardCfgItems,
                        EntryConfig.CarTypeEnumCfgItems,
                        EntryConfig.AppointCheck,
                        EntryConfig.DisableGateControl,
                        EntryConfig.BelowOrEqualStandard5PassStartTime,
                        EntryConfig.BelowOrEqualStandard5PassEndTime,
                        EntryConfig.BelowOrEqualStandard5PassEndTimeInNextDay,
                        EntryConfig.DefaultFreightUnit,
                    }),
                    CreateDate = DateTime.Now
                });
            }
            else
            {
                cfg.StringValue
                    = CommonUtil.AJSerializeObject(new
                    {
                        EntryConfig.EmissionStandardCfgItems,
                        EntryConfig.CarTypeEnumCfgItems,
                        EntryConfig.AppointCheck,
                        EntryConfig.DisableGateControl,
                        EntryConfig.BelowOrEqualStandard5PassStartTime,
                        EntryConfig.BelowOrEqualStandard5PassEndTime,
                        EntryConfig.BelowOrEqualStandard5PassEndTimeInNextDay,
                        EntryConfig.DefaultFreightUnit,
                    });
                db.Entry(cfg).State = EntityState.Modified;
            }
        }

        /// <summary>
        /// 识别配置表单初始化
        /// </summary>
        private void InitCarIdentificationConfigForm()
        {
            _carIdentificationConfig = CommonUtil
                .TryGetJSONObject<CarIdentificationConfig>(db.SystemConfigDictionaries
                .FirstOrDefault(p => p.Key == SystemConfigKey.CarIdentificationConfig)
                ?.StringValue) ?? new CarIdentificationConfig
                {
                    ImageSavePath = CarIdentificationConfig.GetDefaultSavePath(),
                    Type = CarIdentificationConfig.StoreType.本地
                };

            if (_carIdentificationConfig.Type == CarIdentificationConfig.StoreType.本地)
            {
                try
                {
                    if (!Directory.Exists(_carIdentificationConfig.ImageSavePath))
                    {
                        Directory.CreateDirectory(_carIdentificationConfig.ImageSavePath);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show($"配置路径:{_carIdentificationConfig.ImageSavePath};请检查路径或文件夹是否有效:{e.Message}", "识别图片位置初始化失败", MessageBoxButton.OK);
                }
            }

            CarIdentificationConfig_ImageSavePath = _carIdentificationConfig.ImageSavePath;
            CarIdentificationConfig_StoreType = _carIdentificationConfig.Type;
            CarIdentificationConfig_PushUrl = _carIdentificationConfig.PushUrl;

        }

        /// <summary>
        /// 填充更改识别配置表单
        /// </summary>
        private void FillCarIdentificationConfigForm()
        {
            var carIdentificationConfigData = db.SystemConfigDictionaries
                .FirstOrDefault(p => p.Key == SystemConfigKey.CarIdentificationConfig);

            if (CarIdentificationConfig_StoreType == CarIdentificationConfig.StoreType.本地)
            {
                try
                {
                    if (!Directory.Exists(CarIdentificationConfig_ImageSavePath))
                    {
                        Directory.CreateDirectory(CarIdentificationConfig_ImageSavePath);
                    }
                }
                catch (Exception e)
                {
                    ExceptionTool.FriendlyError(e.Message, "车牌识别图片存储配置有误");
                }
            }
            else if (!CommonRegex.IP.IsMatch(CarIdentificationConfig_ImageSavePath))
            {
                ExceptionTool.FriendlyError("请输入正确的IP地址", "车牌识别图片存储配置有误");
            }

            _carIdentificationConfig.ImageSavePath = CarIdentificationConfig_ImageSavePath;
            _carIdentificationConfig.Type = CarIdentificationConfig_StoreType;
            _carIdentificationConfig.PushUrl = CarIdentificationConfig_PushUrl;

            if (carIdentificationConfigData == null)
            {
                db.SystemConfigDictionaries.Add(new SystemConfigDictionary
                {
                    Key = SystemConfigKey.CarIdentificationConfig,
                    StringValue = CommonUtil.AJSerializeObject(_carIdentificationConfig),
                    CreateDate = DateTime.Now
                });
            }
            else
            {
                carIdentificationConfigData.StringValue
                    = CommonUtil.AJSerializeObject(_carIdentificationConfig);
                db.Entry(carIdentificationConfigData).State = EntityState.Modified;
            }
        }

        /// <summary>
        /// 接口配置表单初始化
        /// </summary>
        private void InitThirdpartyCarInfoAPIConfigForm()
        {
            var source = db.SystemConfigDictionaries
                .AsNoTracking().Where(p => p.Key >= SystemConfigKey.APIDefault).ToList();
            var options = new List<AppointAPIBase>();
            foreach (var item in source)
            {
                switch (item.Key)
                {
                    case SystemConfigKey.APIDefault:
                        options.Add(new DefaultAppointAPI(ApplicationType.管理端, item, null));
                        break;
                    case SystemConfigKey.APITangShan:
                        options.Add(new TangShanAppointAPI(ApplicationType.管理端, item, null));
                        break;
                    case SystemConfigKey.APILangFang:
                        options.Add(new LangfangAppointAPI(ApplicationType.管理端, item, null));
                        break;
                    case SystemConfigKey.APIQingDao:
                        options.Add(new QingdaoAppointAPI(ApplicationType.管理端, item, _svcProvider));
                        break;
                    case SystemConfigKey.APIGanZhou:
                        options.Add(new GanzhouAppointAPI(ApplicationType.管理端, item, _svcProvider));
                        break;
                    case SystemConfigKey.APILinYi:
                        options.Add(new LinyiAppointAPI(ApplicationType.管理端, item, _svcProvider));
                        break;
                    case SystemConfigKey.APIBinZhou:
                        options.Add(new BinZhouAppointAPI(ApplicationType.管理端, item, _svcProvider));
                        break;
                    case SystemConfigKey.APIChengDu:
                        options.Add(new ChengDuAppointAPI(ApplicationType.管理端, item, _svcProvider));
                        break;
                    case SystemConfigKey.APIBeiJing:
                        options.Add(new BeiJingAppointAPI(ApplicationType.管理端, item, null));
                        break;
                    case SystemConfigKey.APIQinYou:
                        options.Add(new QinYouAppointAPI(ApplicationType.管理端, item, null));
                        break;
                    case SystemConfigKey.APIDeYang:
                        options.Add(new DeyangAppointAPI(ApplicationType.管理端, item, null));
                        break;
                    default:
                        break;
                }
            }
            APIOptions = new ObservableCollection<AppointAPIBase>(options);
            // 调用一下转换, 好初始化一些配置
            foreach (var item in APIOptions)
            {
                item.Checked = item.Config.BooleanValue;
                item.ConvertToCustomConfig(false);
                if (item is DefaultAppointAPI defaultAPI)
                {
                    GlobalAPIConfig = defaultAPI.APISettings;
                }
            }
            DynamicFormItemSchemas = APIOptions.FirstOrDefault(p => p.Config.BooleanValue).GetSchemas();
        }

        /// <summary>
        /// 填充更改接口配置表单
        /// </summary>
        private void FillThirdPartyCarInfoAPIConfigForm()
        {
            foreach (var item in APIOptions)
            {
                item.UpdateConfig(ref db);
            }
        }
    }

}
